<?php
namespace Admin\Controller;
use Think\Controller;
class CatController extends Controller{
    /**
     * 
     */
    public function cat_list(){
        $catList=D('Cat');
        $catlist=$catList->select();
        $catlist=$catList->getCatTree($catlist,$id=0,$lev=1);//查找子孙树
        $this->assign('catlist',$catlist);
        $this->display();
    }
    /**
     * 
     */
    public function cat_add(){
        $cat=D('Cat');
        if (!IS_POST){
            $addlist=$cat->select();
            $addlist=$cat->getCatTree($addlist,$id=0,$lev=0);
            $this->assign('addlist',$addlist);
            $this->display();
        }
        $info=$cat->create();
        if (!$info){
            //->create()同时完成自动验证和自动完成
            //如果创建失败 表示验证没有通过，输出错误提示信息
            exit(show_bug($cat->getError()));
        }
        $result=$cat->add($info);
        if (!$result){
            $this->error('新增失败');
        }
        $this->redirect('Cat/cat_list');
    }
    /**
     * 
     */
    public function cat_edit(){
        $edit=D('Cat');
        if (!IS_POST){
            $row=$edit->find(I('get.cat_id'));
            $cattree=$edit->select();
            $cattree=$edit->getCatTree($cattree,$id=0,$lev=0);
            $this->assign('row',$row);
            $this->assign('cattree',$cattree);
            $this->display();
        }
        else {
            $info = $edit->where('cat_id=' . I('post.cat_id'))->save(I('post.'));
            if (!info) {
                $this->error('编辑栏目失败');
            }else {
                $this->redirect('Admin/Cat/cat_list');
            }
        }
    }
    /**
     * 
     */
    public function cat_delete(){
        $dele=M('Cat');
        $son=$dele->where('parent_id='.I('get.cat_id'))->select();
        if ($son){
            $this->error('此栏目下有子栏目，不能删除');
        }
        $d=$dele->delete(I('get.cat_id'));
        if ($d){
            $this->redirect('Cat/cat_list');
        }
        $this->error('删除失败');
    }
}